<template>
    <div class="app-container material">
        <el-tabs :value="queryParams.productCategory + ''" :before-leave="onTabChange">
            <el-tab-pane v-for="item in category" :label="item.categoryName" :name="item.categoryId + ''"/>
        </el-tabs>

        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="80px">
            <el-form-item label="物料名称">
                <el-input v-model="queryParams.productName" placeholder="请输入物料名称" clearable/>
            </el-form-item>
            <el-form-item label="物料编号">
                <el-input v-model="queryParams.productNo" placeholder="请输入物料编号" clearable/>
            </el-form-item>
            <el-form-item label="供应商">
                <el-input v-model="queryParams.productSupplier" placeholder="请输入供应商" clearable/>
            </el-form-item>
            <el-form-item label="所属分类">
                <el-select v-model="subCategory" filterable clearable>
                    <el-option v-for="item in subCategoryList" :value="item.categoryId" :label="item.categoryName"/>
                </el-select>
            </el-form-item>
            <el-form-item label="厂家/客户">
                <el-input v-model="queryParams.productCustomer" placeholder="请输入厂家/客户" clearable/>
            </el-form-item>
            <el-form-item label="上架时间">
                <el-date-picker
                    v-model="dateRange"
                    style="width: 215px"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <div class="mb8">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-hasPermi="['oms:product:add']">新建物料
            </el-button>
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="!ids.length"
                       @click="handleDelete" v-hasPermi="['oms:product:remove']">
                删除
            </el-button>
            <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="handleImport">
                批量导入
            </el-button>
            <!--<el-button type="warning" plain icon="el-icon-download" size="mini" @click="downTemplate">下载模板</el-button>-->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </div>

        <el-table v-loading="loading" :data="tableList" @selection-change="onTableSelect" @sort-change="onSortChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="商品信息" prop="productImage" show-overflow-tooltip>
                <div slot-scope="{row}">
                    <div class="table-cell-img">
                        <el-image :src="row.productImage" :preview-src-list="[row.productImage]">
                            <i slot="error" class="el-icon-picture-outline"></i>
                        </el-image>
                    </div>
                    <div>{{ row.productName }}</div>
                </div>
            </el-table-column>
            <el-table-column label="物料编号" prop="productNo"/>
            <el-table-column label="上架时间" prop="createTime" width="170" sortable="custom"/>
            <el-table-column label="剩余库存" prop="productStock" sortable="custom"/>
            <el-table-column label="分类" prop="category.categoryName"/>
             <el-table-column label="厂家/客户" prop="productCustomer"/>
            <el-table-column label="颜色" prop="productColour"/>
            <el-table-column label="规格" prop="productSku"/>
            <el-table-column label="操作" width="200" class-name="small-padding fixed-width">
                <template slot-scope="{row}">
                    <el-button size="mini" type="text" @click="handleDetail(row)">详情</el-button>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleUpdate(row)"
                      v-hasPermi="['oms:product:edit']"
                    >修改</el-button>
                    <el-button size="mini" type="text" @click="handleDelete(row)" v-hasPermi="['oms:product:remove']">
                        删除
                    </el-button>
                    <el-button size="mini" type="text" @click="onStoreHandle(row, stockHandleEnum.in)">
                        入库
                    </el-button>
                    <el-button size="mini" type="text" @click="onStoreHandle(row, stockHandleEnum.out)">出库</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--分页-->
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>

        <!--批量上传导入-->
   <!--     <el-dialog title="批量导入" :visible="showUpload" width="400px" append-to-body
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   @close="uploadClose">
            <file-upload v-model="fileList" :file-size="0" :file-type="['xls','xlsx','XLS','XLSX']" drag/>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="uploadClose">取 消</el-button>
                <el-button type="primary" size="small" @click="onSureImport">确 定</el-button>
            </div>
        </el-dialog> -->

        <!--出库、入库-->
        <el-dialog :title="storeForm.type === stockHandleEnum.in ? '入库' : '出库'" :visible="showStore" width="400px"
                   append-to-body
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   @close="storeClose">
            <el-form :model="storeForm" ref="storeForm" label-position="top">
                <el-form-item :label="'输入' + storeTitle+'数量'" prop="stockNum"
                              :rules="[{ required: true, pattern: IS_INTEGER, message: '请输入正整数'}]">
                    <el-input v-model.number="storeForm.stockNum" placeholder="请输入数量"/>
                </el-form-item>
                <el-form-item label="输入厂家">
                    <el-input v-model="storeForm.productCustomer" placeholder="输入厂家"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="storeClose">取 消</el-button>
                <el-button type="primary" size="small" @click="submitStore">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 物料导入对话框 -->
        <el-dialog :title="upload.title1" :visible.sync="upload.open" width="400px" append-to-body>
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <div class="el-upload__tip" slot="tip">
                <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用物料数据
              </div>
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
            </div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-dialog>
    </div>
</template>

<script>
import {handleEnum, responseEnum, stockHandleEnum} from "../../../const/const";
import {getMaterialList, materialDelete, materialImport, productStock} from "./api";
import AddEdit from "./addEdit"
import {IS_INTEGER} from "../../../utils/validate";
import Api from "./api";
import { getToken } from "@/utils/auth";

import FileUpload from "@/components/FileUpload/"
import {getCategoryList} from "../category/api";

export default {
      name: "Material",
    components: {AddEdit, FileUpload},
    data() {
        return {
            handleEnum,
            IS_INTEGER,
            stockHandleEnum,
            // 日期范围
            dateRange: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                productName: null,
                productSupplier:null,
                productNo: null,
                productCustomer: null,
                productCategory: null,
                orderByColumn: null,
                isAsc: null
            },
            category: [],
            // 二级分类
            subCategoryList: [],
            subCategory: null,
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 物料表格数据
            tableList: [],
            // 选中数组
            ids: [],
            // 新增编辑
            handleType: null,
            currentItem: '',
            // 出库入库
            showStore: false,
            storeTitle: '',
            storeForm: {
                productCustomer: null,
                productId: null,
                stockNum: 0,
                type: null
            },
            // 物料导入参数
            upload: {
              // 是否显示弹出层（物料导入）
              open: false,
              // 弹出层标题（物料导入）
              title1: "物料导入",
              // 是否禁用上传
              isUploading: false,
              // 是否更新已经存在的物料数据
              updateSupport: 0,
              // 设置上传的请求头部
              headers: { Authorization: "Bearer " + getToken() },
              // 上传的地址
              url: process.env.VUE_APP_BASE_API + "/oms/product/importData"
            },
            // 上传
            showUpload: false,
            fileList: [],

        };
    },
    created() {
        // 当前标签优先从路由获取（首页跳转过来带参数）
        this.queryParams.productCategory = this.$route.query.activeTab || this.queryParams.productCategory
        this.getCategory();
    },
    methods: {
        /** 下载模板操作 */
        importTemplate() {
          this.download('oms/product/importTemplate', {
          }, `product_template_${new Date().getTime()}.xlsx`)
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
          this.getList();
        },
        // 提交上传文件
        submitFileForm() {
          this.$refs.upload.submit();
        },
        /** 导入按钮操作 */
        handleImport() {
          this.upload.title = "用户导入";
          this.upload.open = true;
        },

        /** 查询物料列表 */
        getList() {
            this.loading = true;
            const params = _.cloneDeep(this.queryParams);
            params.productCategory = this.subCategory || params.productCategory;
            // console.log(445,this.dateRange)
            getMaterialList(this.addDateRange(params, this.dateRange)).then(res => {
                if (res.code === responseEnum.success) {
                    this.tableList = res.rows || [];
                    this.total = res.total || 0;
                }
            }).finally(() => this.loading = false);
        },
        /** 查询物料分类 */
        getCategory() {
            this.loading = true;
            getCategoryList().then(res => {
                if (res.code === responseEnum.success && res.rows && res.rows.length) {
                    this.category = res.rows;
                    this.queryParams.productCategory = res.rows[0].categoryId;
                }
            }).finally(() => this.getList());
        },
        /**
         * 切换标签
         */
        onTabChange(val) {
            this.queryParams.productCategory = val;
            this.subCategory = null;
            const category = this.category.find(item => item.categoryId == val);
            if (category) {
                this.subCategoryList = category.children;
            }
            this.handleQuery();
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = null;
            this.queryParams = this.$options.data().queryParams;
            this.handleQuery();
        },
        /**
         * 排序
         */
        onSortChange({order, prop}) {
            this.queryParams.orderByColumn = prop;
            this.queryParams.isAsc = order ? order.replace(/ending/, '') : null;
            this.handleQuery();
        },
        /**
         * 多选框选中数据
         */
        onTableSelect(selection) {
            this.ids = selection.map(item => item.productId)
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.$router.push({path: '/material/add', query: {handleType: handleEnum.add}});
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.$router.push({path: '/material/edit', query: {handleType: handleEnum.edit,productId:row.productId}});
        },
        /** 修改按钮操作 */
        handleDetail(row) {
            this.$router.push({
                path: '/material/detail',
                query: {productId: row.productId, handleType: handleEnum.detail}
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            this.$modal.confirm('删除后无法复原，确认删除吗？').then(() => {
                const loading = this.$loading({lock: true});
                materialDelete(row.productId || this.ids.join(',')).then(res => {
                    if (res.code === responseEnum.success) {
                        this.getList();
                        this.$message.success("删除成功");
                    } else {
                        this.$message.error(res.msg);
                    }
                }).finally(() => loading.close())
            });
        },

        /**
         * 出库、入库
         */
        onStoreHandle(row, type) {
            this.currentItem = row;
            this.storeForm.type = type;
            this.showStore = true;
        },
        /**
         * 提交出库入库
         */
        submitStore() {
            this.$refs.storeForm.validate(valid => {
                if (valid) {
                    if (this.storeForm.type === stockHandleEnum.out && this.storeForm.stockNum > this.currentItem.productStock) {
                        this.$message.error(`出库数量不可大于库存（${this.storeForm.stockNum}）`);
                        return;
                    }
                    const data = {...this.storeForm, productId: this.currentItem.productId}
                    const loading = this.$loading({lock: true});
                    productStock(data).then(res => {
                        if (res.code === responseEnum.success) {
                            this.getList();
                            const tips = this.storeForm.type === stockHandleEnum.in ? '入库' : '出库';
                            this.$message.success(`${tips}成功`);
                            this.showStore = false;
                        } else {
                            this.$message.error(res.msg);
                        }
                    }).finally(() => loading.close())
                }
            })
        },
        /**
         * 关闭出库、入库
         */
        storeClose() {
            this.storeForm = this.$options.data().storeForm;
            this.currentItem = '';
            this.showStore = false;
        },
        /** 下载模板 */
        downTemplate() {
            this.download('material/downloadTemplate', {}, `物料模板_${new Date().getTime()}.xlsx`)
        },

        uploadClose() {
            this.showUpload = false;
            this.fileList = [];
        },

        /**
         * 导入
         */
        onSureImport() {
            materialImport({file: this.fileList}).then(res => {
                if (res.code === 200) {
                    this.$message.success('导入成功');
                    this.getList();
                } else {
                    this.$confirm(res.msg, '导入完成', {
                        cancelButtonText: '关闭',
                        confirmButtonText: '下载失败数据',
                    }).then(() => {
                        this.downTemplate()
                    })
                }
            })
        }
    }
};

</script>

<style lang="scss" scoped>

</style>
